import { updateSalary } from '@/api'
import { BaseSelect } from '@/components'
import { SET_SNACKBAR } from '@/store/actions'
import { ColorList, IconList, SalaryFieldsMap, SalaryStatusMap } from '@/store/constant'
import { SalaryItem } from '@/types/common'
import { SelectChangeEvent } from '@mui/material'
import { ChangeEvent } from 'react'
type Props = {
  row: SalaryItem
  refresh: () => void
  renderTrigger?: (props: any) => React.ReactNode
}
const getFormData = (row: SalaryItem) => {
  return pick(row, [...keys(SalaryFormSelects), ...keys(SalaryFieldsMap)])
}

const SalaryFormSelects = {
  status: {
    label: '状态',
    options: values(mapValues(SalaryStatusMap, (v: any, k: string) => ({ label: v.label, value: Number(k) })))
  }
}
const UpdateSalaryButton = ({ row, refresh, renderTrigger }: Props) => {
  const theme = useTheme()
  const dispatch = useDispatch()
  const [open, setOpen] = useState(false)
  const defaultFormData = useMemo(() => {
    return getFormData(row)
  }, [row])

  const [formData, setFormData] = useState<Partial<SalaryItem>>(defaultFormData)

  const handleClose = () => {
    setOpen(false)
  }
  const handleOpen = () => {
    setOpen(true)
  }

  const handleSubmit = () => {
    const data = {
      id: row.id,
      ...formData
    }
    runAsync(data)
  }
  const { runAsync, loading } = useRequest(updateSalary, {
    manual: true,
    debounceWait: 500,
    onFinally(_params: any, _data: any, error: Error | undefined) {
      handleClose()
      dispatch({
        type: SET_SNACKBAR,
        payload: {
          severity: error ? 'error' : 'success',
          children: (
            <>
              <AlertTitle>{error ? '失败: ' + error.message : '操作成功！'}</AlertTitle>
              {row.name}
            </>
          )
        }
      })
      !error && refresh()
    }
  })
  const handleChange = (key: string) => (e: ChangeEvent<HTMLInputElement | HTMLTextAreaElement> | SelectChangeEvent) => {
    const { value } = e.target
    setFormData((prev: any) => ({ ...prev, [key]: isNaN(Number(value)) || value === '' ? value : Number(value) }))
  }

  const fullScreen = useMediaQuery(theme.breakpoints.down('sm'))
  return (
    <>
      {renderTrigger ? (
        renderTrigger({ onClick: handleOpen })
      ) : (
        <Button variant="text" onClick={handleOpen} size="small" color="secondary">
          编辑
        </Button>
      )}
      <Dialog
        fullWidth
        maxWidth="xs"
        fullScreen={fullScreen}
        open={open}
        onClose={handleClose}
        PaperProps={{
          component: 'form',
          onSubmit: (event: React.FormEvent<HTMLFormElement>) => {
            event.preventDefault()

            handleSubmit()
          }
        }}
      >
        <DialogTitle fontSize="1rem">
          编辑 &nbsp;
          <Chip size="small" label={row.name} />
        </DialogTitle>
        <DialogContent>
          <List>
            {toPairs(SalaryFormSelects).map(([field, { label, options }]: [keyof SalaryItem, any], index: number) => {
              const RenderIcon = IconList[index % IconList.length]
              const color = ColorList[index % ColorList.length]
              return (
                <ListItem key={field}>
                  <ListItemAvatar>
                    <Avatar sx={{ bgcolor: color[50] }}>
                      <RenderIcon sx={{ color: color[700] }} />
                    </Avatar>
                  </ListItemAvatar>
                  <ListItemText primary={label} secondary={field} />
                  <BaseSelect
                    size="small"
                    sx={{ width: '6rem', alignSelf: 'end' }}
                    value={formData[field]}
                    label={label}
                    id={field}
                    onChange={handleChange(field)}
                    options={options}
                  />
                </ListItem>
              )
            })}
            <Divider sx={{ marginBlock: 2 }} />
            {toPairs(SalaryFieldsMap).map(([field, label]: [keyof SalaryItem, string], index: number) => {
              const RenderIcon = IconList[index % IconList.length]
              const color = ColorList[index % ColorList.length]
              return (
                <ListItem key={field}>
                  <ListItemAvatar>
                    <Avatar sx={{ bgcolor: color[50] }}>
                      <RenderIcon sx={{ color: color[700] }} />
                    </Avatar>
                  </ListItemAvatar>
                  <ListItemText primary={label} secondary={field} />
                  <TextField
                    size="small"
                    sx={{ width: '6rem', alignSelf: 'end' }}
                    label={label}
                    variant="outlined"
                    type="number"
                    required
                    value={formData[field]}
                    onChange={handleChange(field)}
                    inputProps={{ ...(field === 'released_deposit' && { max: 0 }) }}
                  />
                </ListItem>
              )
            })}
          </List>
        </DialogContent>
        <DialogActions>
          <Button variant="outlined" onClick={handleClose}>
            取消
          </Button>
          <LoadingButton variant="contained" color="secondary" loading={loading} type="submit">
            提交
          </LoadingButton>
        </DialogActions>
      </Dialog>
    </>
  )
}

export default UpdateSalaryButton
